from django.contrib.auth.backends import ModelBackend
from .models import User

class UsernameMobileAuthBackend(ModelBackend):

    def authenticate(self,request, username=None, password=None, **kwargs):

        """
        重写，实现使用用户名或手机号登陆
        :param request: 请求对象
        :param username: 用户名或手机号
        :param password:密码
        :param kwargs:
        :return: 用户对象/None

        """
        # 先按用户名查找 如果没找到 再按手机号查找
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist as e:

            try:
                user = User.objects.get(mobile=username)
            except User.DoesNotExist as e:

                # 没找到 返回none
                return None
        # 找到后 验证密码

        if not user.check_password(password):
            return None

        return user

